package service

import (
	"context"
	"database/sql"
	"strings"

	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/question/glb"
	"google.golang.org/grpc/metadata"
)

func (s *Service) CreateQuestion(ctx context.Context, request *pb.CreateQuestionRequest) (*pb.CreateQuestionResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.CreateQuestionResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	if !token.IsManager {
		chapter := &models.Chapter{UUID: request.GetChapterUUID()}
		managers := make([]models.User, 0, 1)
		err = glb.DB.Model(&chapter.Course).Association("Managers").Find(&managers, "manager_id = ?", token.AccountID)
		if err != nil {
			glb.Logger.Error(err.Error())
			return createQuestionRespSvrErr, nil
		}
		if len(managers) == 0 {
			return &pb.CreateQuestionResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeNotAuth,
				Message: "用户没有权限",
			}}, nil
		}
	}

	question := &models.Question{
		Question:       sql.NullString{String: strings.ToValidUTF8(request.GetQuestion(), ""), Valid: true},
		Analysis:       sql.NullString{String: strings.ToValidUTF8(request.GetAnalysis(), ""), Valid: true},
		AnswerA:        sql.NullString{String: strings.ToValidUTF8(request.GetAnswerA(), ""), Valid: true},
		AnswerB:        sql.NullString{String: strings.ToValidUTF8(request.GetAnswerB(), ""), Valid: true},
		AnswerC:        sql.NullString{String: strings.ToValidUTF8(request.GetAnswerC(), ""), Valid: true},
		AnswerD:        sql.NullString{String: strings.ToValidUTF8(request.GetAnswerD(), ""), Valid: true},
		AnswerE:        sql.NullString{String: strings.ToValidUTF8(request.GetAnswerE(), ""), Valid: true},
		AnswerF:        sql.NullString{String: strings.ToValidUTF8(request.GetAnswerF(), ""), Valid: true},
		AnswerG:        sql.NullString{String: strings.ToValidUTF8(request.GetAnswerG(), ""), Valid: true},
		AnswerH:        sql.NullString{String: strings.ToValidUTF8(request.GetAnswerH(), ""), Valid: true},
		IsA:            sql.NullBool{Bool: request.GetIsA(), Valid: true},
		IsB:            sql.NullBool{Bool: request.GetIsB(), Valid: true},
		IsC:            sql.NullBool{Bool: request.GetIsC(), Valid: true},
		IsD:            sql.NullBool{Bool: request.GetIsD(), Valid: true},
		IsE:            sql.NullBool{Bool: request.GetIsE(), Valid: true},
		IsF:            sql.NullBool{Bool: request.GetIsF(), Valid: true},
		IsG:            sql.NullBool{Bool: request.GetIsG(), Valid: true},
		IsH:            sql.NullBool{Bool: request.GetIsH(), Valid: true},
		IsTrue:         sql.NullBool{Bool: request.GetIsTrue(), Valid: true},
		Type:           sql.NullInt32{Int32: request.GetType(), Valid: true},
		Level:          sql.NullInt32{Int32: request.GetLevel(), Valid: true},
		ChapterUUID:    sql.NullString{String: request.GetChapterUUID(), Valid: true},
		IsExamQuestion: sql.NullBool{Bool: request.GetIsExamQuestion(), Valid: true},
	}

	err = glb.DB.Create(question).Error
	if err != nil {
		if core.IsForeignKeyErr(err) {
			return &pb.CreateQuestionResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "章节不存在",
			}}, nil
		} else if core.IsDuplicateKeyErr(err) {
			return &pb.CreateQuestionResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "此题目已存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return createQuestionRespSvrErr, nil
	}

	return &pb.CreateQuestionResponse{
		Status: &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
		UUID:   question.UUID,
	}, nil
}
